

package cn.shengchao.examstar.distribute.ohs.local.appservice.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.shengchao.base.enums.DisEnableStatusEnum;
import cn.shengchao.base.enums.ProductType;
import cn.shengchao.base.lock.DistributedLock;
import cn.shengchao.base.lock.LockException;
import cn.shengchao.base.lock.ZLock;
import cn.shengchao.examstar.distribute.infrastrure.po.*;
import cn.shengchao.examstar.distribute.infrastrure.service.*;
import cn.shengchao.examstar.distribute.ohs.local.appservice.DistributeOrderDomainService;
import cn.shengchao.examstar.rpc.distribute.cs.DistributeBusinessLockKeyCs;
import cn.shengchao.examstar.rpc.distribute.dto.DistributeOrderContentDto;
import cn.shengchao.examstar.rpc.distribute.dto.DistributeOrderTaskDto;
import cn.shengchao.examstar.rpc.distribute.enums.*;
import cn.shengchao.examstar.rpc.orders.api.IOrderRpc;
import cn.shengchao.examstar.rpc.orders.res.PayOrderInfoDto;
import cn.shengchao.examstar.rpc.orders.res.PayOrderItemInfoDto;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.continew.starter.core.exception.BaseException;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static cn.shengchao.examstar.rpc.distribute.enums.DistributeOrderTaskStatusDataStatusEnum.*;

/**
 * @program: examstarapi
 * @description: 订单分账的综合业务处理
 * @author: Xiong weiqiang
 * @create: 2025-03-28 14:01
 */
@Service
@RequiredArgsConstructor
public class DistributeOrderDomainServiceImpl implements DistributeOrderDomainService {
    private final DistributeOrderTaskService distributeOrderTaskService;
    private final DistributeOrderTaskContentService distributeOrderTaskContentService;
    private final DistributeOrderTaskSaleService distributeOrderTaskSaleService;
    private final DistributeUserInviteService distributeUserInviteService;
    private final DistributeNodeInfoService distributeNodeInfoService;
    private final DistributeContentInfoService distributeContentInfoService;
    private final DistributeNodeRoleChainService distributeNodeRoleChainService;
    private final DistributeNodeRoleService distributeNodeRoleService;
    private final DistributeOrderTaskLogService distributeOrderTaskLogService;
    private final DistributeContentProductThirdService distributeContentProductThirdService;
    private final DistributeTaskPrepareContentService distributeTaskPrepareContentService;
    private final DistributeTaskPrepareSaleService distributeTaskPrepareSaleService;
    private final DistributedLock distributedLock;
    @DubboReference
    private final IOrderRpc orderRpc;

    /**
     * method : createDistributeOrderTask
     * description : 接收订单任务，不管怎么样先存着，以免丢失记录
     *
     * @param distributeOrderTaskDto \{@link DistributeOrderTaskDto \}
     * @author : Xiong weiqiang
     * @CreateDate : 2025-03-28 15:51:50
     * @Reviewed :
     * @UpdateLog : Name Date Reason/Contents
     * ---------------------------------------
     * **** **** ****
     */
    @Transactional
    @Override
    public void createDistributeOrderTask(DistributeOrderTaskDto distributeOrderTaskDto) {
        if (distributeOrderTaskDto == null) {
            throw new BaseException("创建订单任务失败：订单任务对象为空");

        }
        ZLock zLock = null;
        try {
            zLock = distributedLock.tryLock(DistributeBusinessLockKeyCs.DISTRIBUTE_ORDER_TASK_RECEIVE_LOCK_KEY + distributeOrderTaskDto.getOrderId(), 3, TimeUnit.SECONDS);
            if (zLock == null) {
                throw new LockException("创建订单任务失败：获取锁失败");
            }
            long count = distributeOrderTaskService.count(Wrappers.lambdaQuery(DistributeOrderTask.class)
                    .eq(DistributeOrderTask::getOrderId, distributeOrderTaskDto.getOrderId()));
            if (count > 0) {
                throw new BaseException("创建订单任务失败：订单任务已存在");
            }
            DistributeOrderTask distributeOrderTask = new DistributeOrderTask();
            BeanUtil.copyProperties(distributeOrderTaskDto, distributeOrderTask);
            distributeOrderTask.setId(null);
            if (distributeOrderTask.getDistributeOrderAmount().doubleValue()>0){
                distributeOrderTask.setDataStatus(STATUS_CREATE.getStatus());
            }else {
                //订单金额为0，免费的不去分了
                distributeOrderTask.setDataStatus(STATUS_ASGNED.getStatus());
            }
            distributeOrderTaskService.save(distributeOrderTask);
            processOrderDistributeUserAndPercent(distributeOrderTask, distributeOrderTaskDto.getOrderId());
        } catch (Exception e) {
            if (e instanceof LockException) {
                throw new BaseException("创建订单任务失败：任务忙");
            } else if (e instanceof BaseException) {
                throw (BaseException) e;
            } else {
                e.printStackTrace();
                throw new BaseException("创建订单任务失败：未知异常");
            }
        } finally {
            if (zLock != null) {
                try {
                    zLock.close();
                } catch (Exception e) {
                    throw new BaseException("创建订单任务失败：订单任务锁释放失败");
                }
            }
        }
    }
    private void processOrderDistributeUserAndPercent(DistributeOrderTask distributeOrderTask, Long orderId){
        PayOrderInfoDto orderInfo=orderRpc.getOrderInfoDto(orderId);
        if (orderInfo!=null){
            //首先，通过邀请和服务关系找到订单客户的分成人
            List<DistributeUserInvite> distributeUserInvites = distributeUserInviteService.list(Wrappers
                    .lambdaQuery(DistributeUserInvite.class)
                    .eq(DistributeUserInvite::getUserId, orderInfo.getUserId())
                    .eq(DistributeUserInvite::getDataStatus, DistributeDataValidEnum.STATUS_VALID.getStatus()));
            List<DistributeTaskPrepareContent> distributeTaskPrepareContents = new ArrayList<>();
            List<DistributeTaskPrepareSale> distributeTaskPrepareSales = new ArrayList<>();
            //内容产品固定分销情况
            if (orderInfo.getProductType()!=null){
                List<PayOrderItemInfoDto> payOrderItemInfoDtos=new ArrayList<>();
                List<String> productIds=new ArrayList<>();
                //课程
                if (orderInfo.getProductType().equals(ProductType.COURSE.name())){
                    if (CollUtil.isNotEmpty(orderInfo.getOrderItemInfos())){
                        payOrderItemInfoDtos=orderInfo.getOrderItemInfos();
                        productIds=orderInfo.getOrderItemInfos().stream().map(PayOrderItemInfoDto::getProductId).toList();
                        //有子订单按子订单查

                    }else {
                        productIds.add(orderInfo.getProductId());
                        PayOrderItemInfoDto mainOrderToItemDto = new PayOrderItemInfoDto();
                        mainOrderToItemDto.setId(0L);
                        mainOrderToItemDto.setProductId(orderInfo.getProductId());
                        mainOrderToItemDto.setProductName(orderInfo.getProductName());
                        mainOrderToItemDto.setOrderId(orderInfo.getOrderId());
                        mainOrderToItemDto.setOrderTime(orderInfo.getOrderTime());
                        mainOrderToItemDto.setPrice(orderInfo.getPrice());
                        mainOrderToItemDto.setTotalAmount(orderInfo.getTotalAmount());
                        mainOrderToItemDto.setStatus(orderInfo.getStatus());
                        mainOrderToItemDto.setProductInfo(orderInfo.getProductInfo());
                        payOrderItemInfoDtos.add(mainOrderToItemDto);
                        //无子订单按主订单查
                    }

                    //查出所有的代理
                    List<DistributeContentInfo> distributeContentInfos = distributeContentInfoService.list(Wrappers
                            .lambdaQuery(DistributeContentInfo.class)
                            .in(DistributeContentInfo::getContentId, productIds)
                            .eq(DistributeContentInfo::getDataStatus, DistributeDataValidEnum.STATUS_VALID.getStatus()));
                    distributeOrderTask.setContentDistributeNum(CollUtil.isEmpty(distributeContentInfos)?0:distributeContentInfos.size());
                    Set<Long> distributeUserIds=distributeContentInfos.stream().map(DistributeContentInfo::getAuthorUserId).collect(Collectors.toSet());
                    if (CollUtil.isNotEmpty(distributeUserIds)){
                        List<DistributeNodeInfo> distributeNodeInfos=distributeNodeInfoService.list(Wrappers.lambdaQuery(DistributeNodeInfo.class)
                                .in(DistributeNodeInfo::getUserId, distributeUserIds)
                                .eq(DistributeNodeInfo::getDataStatus, DistributeDataValidEnum.STATUS_VALID.getStatus()));

                        Map<Long, List<DistributeContentInfo>> distributeContentInfoMap = distributeContentInfos.stream().collect(Collectors.groupingBy(DistributeContentInfo::getContentId));
                        Map<Long, DistributeNodeInfo> distributeNodeInfoMap = distributeNodeInfos.stream().collect(Collectors.toMap(DistributeNodeInfo::getUserId, v -> v, (v1, v2) -> v2  ));

                        for (PayOrderItemInfoDto itemInfoDto: payOrderItemInfoDtos){
                            List<DistributeContentInfo> distributeContentInfoList = distributeContentInfoMap.get(Long.parseLong(itemInfoDto.getProductId()));
                            if (CollUtil.isEmpty(distributeContentInfoList)){
                                DistributeTaskPrepareContent distributeTaskPrepareContent=new DistributeTaskPrepareContent();
                                distributeTaskPrepareContent.setProductType(orderInfo.getProductType());
                                distributeTaskPrepareContent.setOrderId(orderId);
                                distributeTaskPrepareContent.setProductId(Long.parseLong(itemInfoDto.getProductId()));
                                distributeTaskPrepareContent.setPayItemId(itemInfoDto.getId());
                                distributeTaskPrepareContent.setDistributeTaskId(distributeOrderTask.getId());
                                distributeTaskPrepareContent.setAuthorUserId(0L);
                                distributeTaskPrepareContent.setStablePercent(BigDecimal.ZERO);
                                distributeTaskPrepareContent.setDistributeContentNodeId(0L);
                                distributeTaskPrepareContents.add(distributeTaskPrepareContent);
                            }else {
                                for (DistributeContentInfo distributeContentInfo: distributeContentInfoList){
                                    DistributeNodeInfo distributeNodeInfo = distributeNodeInfoMap.get(distributeContentInfo.getAuthorUserId());
                                    DistributeTaskPrepareContent distributeTaskPrepareContent=new DistributeTaskPrepareContent();
                                    distributeTaskPrepareContent.setProductType(orderInfo.getProductType());
                                    distributeTaskPrepareContent.setOrderId(orderId);
                                    distributeTaskPrepareContent.setProductId(Long.parseLong(itemInfoDto.getProductId()));
                                    distributeTaskPrepareContent.setPayItemId(itemInfoDto.getId());
                                    distributeTaskPrepareContent.setDistributeTaskId(distributeOrderTask.getId());
                                    distributeTaskPrepareContent.setDistributeContentId(distributeContentInfo==null?0L:distributeContentInfo.getId());
                                    distributeTaskPrepareContent.setStatus(0);
                                    if (distributeContentInfo!=null){
                                        distributeTaskPrepareContent.setAuthorUserId(distributeContentInfo.getAuthorUserId());
                                        distributeTaskPrepareContent.setStablePercent(distributeContentInfo.getStablePercent());
                                        distributeTaskPrepareContent.setDistributeContentNodeId(distributeNodeInfo==null?0L:distributeNodeInfo.getId());
                                    }else {
                                        distributeTaskPrepareContent.setAuthorUserId(0L);
                                        distributeTaskPrepareContent.setStablePercent(BigDecimal.ZERO);
                                        distributeTaskPrepareContent.setDistributeContentNodeId(0L);
                                    }
                                    distributeTaskPrepareContents.add(distributeTaskPrepareContent);
                                }
                            }
                        }
                    }
                }
                //第三方会员
                else if (Arrays.asList(ProductType.PRODUCT_THIRD_YCBDC.name(),ProductType.PRODUCT_THIRD_CAP.name()).contains(orderInfo.getProductType())){
                    if (CollUtil.isNotEmpty(orderInfo.getOrderItemInfos())){
                        payOrderItemInfoDtos=orderInfo.getOrderItemInfos();
                        productIds=orderInfo.getOrderItemInfos().stream().map(PayOrderItemInfoDto::getProductId).toList();
                        //有子订单按子订单查

                    }else {
                        productIds.add(orderInfo.getProductId());
                        PayOrderItemInfoDto mainOrderToItemDto = new PayOrderItemInfoDto();
                        mainOrderToItemDto.setId(0L);
                        mainOrderToItemDto.setProductId(orderInfo.getProductId());
                        mainOrderToItemDto.setProductName(orderInfo.getProductName());
                        mainOrderToItemDto.setOrderId(orderInfo.getOrderId());
                        mainOrderToItemDto.setOrderTime(orderInfo.getOrderTime());
                        mainOrderToItemDto.setPrice(orderInfo.getPrice());
                        mainOrderToItemDto.setTotalAmount(orderInfo.getTotalAmount());
                        mainOrderToItemDto.setStatus(orderInfo.getStatus());
                        mainOrderToItemDto.setProductInfo(orderInfo.getProductInfo());
                        payOrderItemInfoDtos.add(mainOrderToItemDto);
                        //无子订单按主订单查
                    }

                    //查出所有的代理
                    List<DistributeContentProductThird> distributeContentProductThirds = distributeContentProductThirdService.list(Wrappers
                            .lambdaQuery(DistributeContentProductThird.class)
                            .in(DistributeContentProductThird::getProductId, orderInfo.getProductId())
                            .eq(DistributeContentProductThird::getDataStatus, DistributeDataValidEnum.STATUS_VALID.getStatus()));
                    if (CollUtil.isEmpty(distributeContentProductThirds)){
                        distributeOrderTask.setContentDistributeNum(0);
                    }else {
                        distributeOrderTask.setContentDistributeNum(distributeContentProductThirds.size());
                    }
                    Set<Long> distributeUserIds=distributeContentProductThirds.stream().map(DistributeContentProductThird::getUserId).collect(Collectors.toSet());
                    List<DistributeNodeInfo> distributeNodeInfos=distributeNodeInfoService.list(Wrappers.lambdaQuery(DistributeNodeInfo.class)
                            .in(DistributeNodeInfo::getUserId, distributeUserIds)
                            .eq(DistributeNodeInfo::getDataStatus, DistributeDataValidEnum.STATUS_VALID.getStatus()));

                    Map<Long, List<DistributeContentProductThird>> distributeContentInfoMap = distributeContentProductThirds.stream().collect(Collectors.groupingBy(DistributeContentProductThird::getProductId));
                    Map<Long, DistributeNodeInfo> distributeNodeInfoMap = distributeNodeInfos.stream().collect(Collectors.toMap(DistributeNodeInfo::getUserId, v -> v, (v1, v2) -> v2  ));

                    for (PayOrderItemInfoDto itemInfoDto: payOrderItemInfoDtos){
                        List<DistributeContentProductThird> distributeContentInfoList = distributeContentInfoMap.get(Long.parseLong(itemInfoDto.getProductId()));
                        if (CollUtil.isEmpty(distributeContentInfoList)){
                            DistributeTaskPrepareContent distributeTaskPrepareContent=new DistributeTaskPrepareContent();
                            distributeTaskPrepareContent.setProductType(orderInfo.getProductType());
                            distributeTaskPrepareContent.setOrderId(orderId);
                            distributeTaskPrepareContent.setProductId(Long.parseLong(itemInfoDto.getProductId()));
                            distributeTaskPrepareContent.setPayItemId(itemInfoDto.getId());
                            distributeTaskPrepareContent.setDistributeTaskId(distributeOrderTask.getId());
                            distributeTaskPrepareContent.setAuthorUserId(0L);
                            distributeTaskPrepareContent.setStablePercent(BigDecimal.ZERO);
                            distributeTaskPrepareContent.setDistributeContentNodeId(0L);
                            distributeTaskPrepareContents.add(distributeTaskPrepareContent);
                        }else {
                            for (DistributeContentProductThird distributeContentInfo: distributeContentInfoList){
                                DistributeNodeInfo distributeNodeInfo = distributeNodeInfoMap.get(distributeContentInfo.getUserId());
                                DistributeTaskPrepareContent distributeTaskPrepareContent=new DistributeTaskPrepareContent();
                                distributeTaskPrepareContent.setProductType(orderInfo.getProductType());
                                distributeTaskPrepareContent.setOrderId(orderId);
                                distributeTaskPrepareContent.setProductId(Long.parseLong(itemInfoDto.getProductId()));
                                distributeTaskPrepareContent.setPayItemId(itemInfoDto.getId());
                                distributeTaskPrepareContent.setDistributeTaskId(distributeOrderTask.getId());
                                distributeTaskPrepareContent.setDistributeContentId(distributeContentInfo==null?0L:distributeContentInfo.getId());
                                distributeTaskPrepareContent.setStatus(0);
                                if (distributeContentInfo!=null){
                                    distributeTaskPrepareContent.setAuthorUserId(distributeContentInfo.getUserId());
                                    distributeTaskPrepareContent.setStablePercent(distributeContentInfo.getStablePercent());
                                    distributeTaskPrepareContent.setDistributeContentNodeId(distributeNodeInfo==null?0L:distributeNodeInfo.getId());
                                }else {
                                    distributeTaskPrepareContent.setAuthorUserId(0L);
                                    distributeTaskPrepareContent.setStablePercent(BigDecimal.ZERO);
                                    distributeTaskPrepareContent.setDistributeContentNodeId(0L);
                                }
                                distributeTaskPrepareContents.add(distributeTaskPrepareContent);
                            }
                        }
                    }
                }
                //平台会员
                else if (orderInfo.getProductType().equals(ProductType.PRODUCT_MEMBER.name())){
                    distributeOrderTask.setContentDistributeNum(0);
                }else {
                    distributeOrderTask.setContentDistributeNum(0);
                }
                distributeTaskPrepareContentService.saveBatch(distributeTaskPrepareContents);
                if (CollUtil.isNotEmpty(distributeUserInvites)){
                    Long sourceSaleUserId = distributeUserInvites.getFirst().getInviteUserId();
                    int error=0;
                    if (sourceSaleUserId != null &&sourceSaleUserId > 0L) {

                        //修改为以直接邀请人inviteUserId作为分成人。
                        // 修改20250503 订单的分成人，修改为直接邀请人inviteUserId作为分成人：saleUserId可以是员工，
                        // 员工的distributeUserId上有不同，如果是员工，distributeUserId是加盟商，角色是分销商员工。其他是分给自己的。
                        // distributeUserId如果跟分成人不一样，那么就是机构分成人（机构下的会员，员工）
                        // distributeUserId如果跟分成人一样，那么就是机构自己发展的，或者是平台，平台会员发展的。
                        // 市场经理是管理机构的，所以市场经理只能从机构分成。
                        // 又产生了新的情况，如果分销商员工禁用了，分销商还是得分成，还得记录。
                        DistributeNodeInfo distributeNodeInfo = distributeNodeInfoService.getNodeInfoForUser(sourceSaleUserId, DistributeTypeEnum.TYPE_SALE);
                        if (distributeNodeInfo!= null) {

                            //找到分销链。
                            List<Long> userIdList = distributeNodeRoleChainService.selectSaleChainUserIds(sourceSaleUserId);
                            List<DistributeNodeInfo> distributeNodeInfos = distributeNodeInfoService.list(Wrappers
                                    .lambdaQuery(DistributeNodeInfo.class)
                                    .eq(DistributeNodeInfo::getDataStatus, DistributeDataStatusEnum.STATUS_CURT.getStatus())
                                    .in(DistributeNodeInfo::getUserId, userIdList)
                                    .eq(DistributeNodeInfo::getDistributeType, DistributeTypeEnum.TYPE_SALE
                                            .getType()));
                            List<DistributeNodeRole> distributeNodeRoles = distributeNodeRoleService.list(Wrappers
                                    .lambdaQuery(DistributeNodeRole.class)
                                    .eq(DistributeNodeRole::getDataStatus, DistributeDataStatusEnum.STATUS_CURT.getStatus())
                                    .in(DistributeNodeRole::getUserId, userIdList)
                                    .eq(DistributeNodeRole::getDistributeType, DistributeTypeEnum.TYPE_SALE
                                            .getType()));
                            if (CollUtil.isNotEmpty(distributeNodeInfos)){
                                distributeOrderTask.setSaleDistributeNum(distributeNodeInfos.size());
                                for (DistributeNodeInfo nodeInfo: distributeNodeInfos){
                                    Optional<DistributeNodeRole> distributeNodeRole=distributeNodeRoles.stream().filter(item->item.getUserId().equals(nodeInfo.getUserId())).findFirst();
                                    DistributeTaskPrepareSale distributeTaskPrepareContent=new DistributeTaskPrepareSale();
                                    distributeTaskPrepareContent.setOrderId(orderId);
                                    distributeTaskPrepareContent.setDistributeInviteId(CollUtil.isNotEmpty(distributeUserInvites)?distributeUserInvites.getFirst().getId():0L);
                                    distributeTaskPrepareContent.setSaleDistributeUserId(nodeInfo.getUserId());
                                    distributeTaskPrepareContent.setOrderId(orderId);
                                    distributeTaskPrepareContent.setStatus(0);
                                    distributeTaskPrepareContent.setStablePercent(distributeNodeRole.isPresent()?distributeNodeRole.get().getPercentStable():BigDecimal.ZERO);
                                    distributeTaskPrepareContent.setDistributeTaskId(distributeOrderTask.getId());
                                    distributeTaskPrepareContent.setSaleDistributeNodeId(nodeInfo.getUserId());
                                    distributeTaskPrepareSales.add(distributeTaskPrepareContent);
                                }

                            }else {
                                error=1;
                            }

                        }else {
                            error=1;
                        }
                    }else if (sourceSaleUserId == 0L) {
                        distributeOrderTask.setSaleDistributeNum(0);
                        DistributeTaskPrepareSale distributeTaskPrepareContent=new DistributeTaskPrepareSale();
                        distributeTaskPrepareContent.setOrderId(orderId);
                        distributeTaskPrepareContent.setDistributeInviteId(CollUtil.isNotEmpty(distributeUserInvites)?distributeUserInvites.getFirst().getId():0L);
                        distributeTaskPrepareContent.setSaleDistributeUserId(0L);
                        distributeTaskPrepareContent.setOrderId(orderId);
                        distributeTaskPrepareContent.setStatus(0);
                        distributeTaskPrepareContent.setStablePercent(BigDecimal.ZERO);
                        distributeTaskPrepareContent.setDistributeTaskId(distributeOrderTask.getId());
                        distributeTaskPrepareContent.setSaleDistributeNodeId(0L);
                        distributeTaskPrepareSales.add(distributeTaskPrepareContent);
                    }else {
                        error=1;
                    }
                    if (error==1){
                        distributeOrderTask.setSaleDistributeNum(0);
                        DistributeTaskPrepareSale distributeTaskPrepareContent=new DistributeTaskPrepareSale();
                        distributeTaskPrepareContent.setOrderId(orderId);
                        distributeTaskPrepareContent.setDistributeInviteId(CollUtil.isNotEmpty(distributeUserInvites)?distributeUserInvites.getFirst().getId():0L);
                        distributeTaskPrepareContent.setSaleDistributeUserId(0L);
                        distributeTaskPrepareContent.setOrderId(orderId);
                        distributeTaskPrepareContent.setStatus(4);
                        distributeTaskPrepareContent.setStablePercent(BigDecimal.ZERO);
                        distributeTaskPrepareContent.setDistributeTaskId(distributeOrderTask.getId());
                        distributeTaskPrepareContent.setSaleDistributeNodeId(0L);
                        distributeTaskPrepareSales.add(distributeTaskPrepareContent);
                    }
                }else {
                    distributeOrderTask.setSaleDistributeNum(0);
                    DistributeTaskPrepareSale distributeTaskPrepareContent=new DistributeTaskPrepareSale();
                    distributeTaskPrepareContent.setOrderId(orderId);
                    distributeTaskPrepareContent.setDistributeInviteId(CollUtil.isNotEmpty(distributeUserInvites)?distributeUserInvites.getFirst().getId():0L);
                    distributeTaskPrepareContent.setSaleDistributeUserId(0L);
                    distributeTaskPrepareContent.setOrderId(orderId);
                    distributeTaskPrepareContent.setStatus(0);
                    distributeTaskPrepareContent.setStablePercent(BigDecimal.ZERO);
                    distributeTaskPrepareContent.setDistributeTaskId(distributeOrderTask.getId());
                    distributeTaskPrepareContent.setSaleDistributeNodeId(0L);
                    distributeTaskPrepareSales.add(distributeTaskPrepareContent);
                }
                distributeTaskPrepareSaleService.saveBatch(distributeTaskPrepareSales);
            }
        }
        distributeOrderTaskService.update(Wrappers.lambdaUpdate(DistributeOrderTask.class)
                .eq(DistributeOrderTask::getOrderId, distributeOrderTask.getOrderId())
                .set(DistributeOrderTask::getSaleDistributeNum, distributeOrderTask.getSaleDistributeNum())
                .set(DistributeOrderTask::getContentDistributeNum, distributeOrderTask.getContentDistributeNum()));
    }
    /**
     * method : processContentDistributeOrderTask
     * description : 具体分账业务逻辑
     *
     * @param taskId              \{@link Long \}
     * @param orderId             \{@link Long \}
     * @param orderContentDtoList \{@link List< DistributeOrderContentDto> \}
     * @author : Xiong weiqiang
     * @CreateDate : 2025-03-28 15:52:28
     * @Reviewed :
     * @UpdateLog : Name Date Reason/Contents
     * ---------------------------------------
     * **** **** ****
     */
    @Transactional
    @Override
    public void processContentDistributeOrderTask(Long taskId,
                                                  Long orderId,
                                                  List<DistributeOrderContentDto> orderContentDtoList) {
        ZLock zLock = null;
        try {
            zLock = distributedLock.tryLock(DistributeBusinessLockKeyCs.DISTRIBUTE_ORDER_TASK_CAL_LOCK_KEY + taskId, 3, TimeUnit.SECONDS);
            if (zLock == null) {
                throw new LockException("订单任务分销计算失败：获取锁失败");
            }
            DistributeOrderTask distributeOrderTask = distributeOrderTaskService.getById(taskId);
            if (distributeOrderTask == null) {
                distributeOrderTaskLogService.logError(taskId, orderId, "订单id:" + orderId + "没有找到订单任务信息");
                return;
            }
            if (!distributeOrderTask.getDataStatus().equals(STATUS_INASGN.getStatus())) {
                distributeOrderTaskLogService.logError(taskId, orderId, "订单id:" + orderId + "任务状态不匹配：" + distributeOrderTask
                        .getDataStatus());
                return;
            }
            if (CollUtil.isEmpty(orderContentDtoList)) {
                distributeOrderTaskLogService.logError(taskId, orderId, "订单id:" + orderId + "没有找到订单内容组成信息");
                return;
            }
            DistributeOrderContentCalResult distributeOrderContentCalResult = calDistributeOrderTaskContent(taskId, orderId, orderContentDtoList);
            if (!distributeOrderContentCalResult.getResult()) {
                distributeOrderTaskLogService.logError(taskId, orderId, distributeOrderContentCalResult.getMessage());
            } else {
                DistributeOrderSaleCalResult distributeOrderSaleCalcResult = calDistributeOrderTaskSale(taskId, orderId);
                if (!distributeOrderSaleCalcResult.getResult()) {
                    distributeOrderTaskLogService.logError(taskId, orderId, distributeOrderSaleCalcResult.getMessage());
                } else {
                    BigDecimal distributeOrderAmount = distributeOrderTask.getDistributeOrderAmount();
                    BigDecimal distributeSaleAmount = distributeOrderSaleCalcResult.getDistributeOrderTask().getDistributeSaleAmount();
                    //分成总额
                    BigDecimal distributeContentAmount = distributeOrderContentCalResult.getDistributeOrderTask().getDistributeContentAmount();
                    if (distributeOrderAmount.doubleValue() > (distributeSaleAmount.add(distributeContentAmount)).doubleValue()) {
                        DistributeOrderTask distributeOrderTaskFinal = distributeOrderSaleCalcResult.getDistributeOrderTask();
                        distributeOrderTaskFinal.setDistributeContentAmount(distributeOrderContentCalResult.getDistributeOrderTask().getDistributeContentAmount());
                        String message = distributeOrderContentCalResult.getMessage().concat("|" + distributeOrderSaleCalcResult.getMessage());
                        distributeOrderTaskContentService.saveBatch(distributeOrderContentCalResult.getDistributeOrderTaskContents());
                        distributeOrderTaskSaleService.saveBatch(distributeOrderSaleCalcResult.getDistributeOrderTaskSales());
                        distributeOrderTaskLogService.logSuccess(taskId, orderId, message);
                        distributeOrderTaskService.updateById(distributeOrderTaskFinal);
                    } else {
                        distributeOrderTaskLogService.logError(taskId, orderId, "分成超过额度：销售分成总额：" + distributeSaleAmount + ",内容分成总额：" + distributeContentAmount);
                    }
                }

            }
        } catch (Exception e) {
            if (e instanceof LockException) {
                throw new BaseException("订单任务分销计算失败：任务忙");
            } else if (e instanceof BaseException) {
                throw (BaseException) e;
            } else {
                e.printStackTrace();
                throw new BaseException("订单任务分销计算失败：未知异常");
            }
        } finally {
            if (zLock != null) {
                try {
                    zLock.close();
                } catch (Exception e) {
                    throw new BaseException("订单任务分销计算失败：订单任务锁释放失败");
                }
            }
        }
    }

    /**
     * method : calDistributeOrderTaskContent
     * description : 处理内容分销的计算
     *
     * @param taskId              \{@link Long \}
     * @param orderId             \{@link Long \}
     * @param orderContentDtoList \{@link DistributeOrderContentDto \}
     * @author : Xiong weiqiang
     * @CreateDate : 2025-05-03 15:52:28
     * @Reviewed :
     * @UpdateLog : Name Date Reason/Contents
     * ---------------------------------------
     * **** **** ****
     */
    private DistributeOrderContentCalResult calDistributeOrderTaskContent(Long taskId, Long orderId,
                                                                          List<DistributeOrderContentDto> orderContentDtoList) {
        DistributeOrderTask distributeOrderTask = distributeOrderTaskService.getById(taskId);
        List<String> contentIds = new ArrayList<>(orderContentDtoList.stream()
                .map(DistributeOrderContentDto::getProductId)
                .toList());


        BigDecimal distributeOrderAmount = distributeOrderTask.getDistributeOrderAmount();
        BigDecimal distributeContentAmount = new BigDecimal(0);
        String chainRecords = "";
        List<DistributeContentInfo> distributeContentInfos = distributeContentInfoService.list(Wrappers
                .lambdaQuery(DistributeContentInfo.class)
                .eq(DistributeContentInfo::getDataStatus, DistributeDataStatusEnum.STATUS_CURT.getStatus())
                .in(DistributeContentInfo::getContentId, contentIds));
        List<DistributeOrderTaskContent> distributeOrderTaskContents = new ArrayList<>();
        chainRecords = chainRecords + "内容分成：";
        //首先计算内容分成
        if (CollUtil.isNotEmpty(distributeContentInfos)) {
            //找出分成的人
            List<Long> userIdList = distributeContentInfos.stream()
                    .map(DistributeContentInfo::getAuthorUserId)
                    .toList();
            chainRecords = chainRecords + "作者：" + JSONUtil.toJsonStr(userIdList);
            List<DistributeNodeInfo> distributeNodeInfos = distributeNodeInfoService.list(Wrappers
                    .lambdaQuery(DistributeNodeInfo.class)
                    .eq(DistributeNodeInfo::getDataStatus, DistributeDataStatusEnum.STATUS_CURT.getStatus())
                    .in(DistributeNodeInfo::getUserId, userIdList)
                    .eq(DistributeNodeInfo::getDistributeType, DistributeTypeEnum.TYPE_CTPD.getType()));
            Map<Long, DistributeNodeInfo> orderContentNodeMap = distributeNodeInfos.stream()
                    .collect(Collectors.toMap(DistributeNodeInfo::getUserId, item -> item));
            Map<String, DistributeOrderContentDto> orderContentDtoMap = orderContentDtoList.stream()
                    .collect(Collectors.toMap(DistributeOrderContentDto::getProductId, item -> item));

            BigDecimal contentSum = new BigDecimal(0);
            Date orderTime=CollUtil.isNotEmpty(orderContentDtoList)?orderContentDtoList.get(0).getOrderTime():distributeOrderTask.getOrderTime();
            for (DistributeOrderContentDto distributeOrderContentDto : orderContentDtoList) {
                contentSum = contentSum.add(distributeOrderContentDto.getProductAmount());
            }
            // 循环每一个课程，计算佣金
            for (DistributeContentInfo contentInfo : distributeContentInfos) {
                Long contentId = contentInfo.getContentId();
                //订单里每个内容都有一个内容拆分出来的金额
                DistributeOrderContentDto distributeOrderContentDto = orderContentDtoMap.get(contentId.toString());
                if (distributeOrderContentDto == null) {
                    chainRecords = chainRecords + "，内[" + contentId + "]无记录,";
                    continue;
                }
                //改成内容作者，反正他也是挂内容分销商名下的。
                DistributeNodeInfo distributeNodeInfo = orderContentNodeMap.get(contentInfo
                        .getAuthorUserId());
                //分销员工要跳过，修改：不跳过了，就按作者计算，不然一样显示不了
//                    if (distributeNodeInfo.getDistributeRoleCode().equals(DistributeSaleRoleEnum.ROLE_DSPD_EMP.getCode())){
//                        continue;
//                    }
                if (!distributeNodeInfo.getEnableStatus().equals(DisEnableStatusEnum.ENABLE.getValue())) {
                    chainRecords = chainRecords + "，[" + distributeNodeInfo.getUserId() + "]状态失效,";
                    continue;
                }
                if (!DateUtil.isIn(orderTime, contentInfo.getValidStartTime(), contentInfo.getValidEndTime())) {
                    chainRecords = chainRecords + "，[" + contentInfo.getAuthorUserId() + "]时间失效,";
                    continue;
                }
                //内容金额与订单金额不相同，需要计算比例
                BigDecimal orderContentAmount = distributeOrderContentDto.getProductAmount();

                if (contentSum.doubleValue() == 0d) {
                    //内容总额为0
                    orderContentAmount = BigDecimal.ZERO;
                } else {
                    //内容额是单品额在总价的占比
                    orderContentAmount = distributeOrderAmount.multiply(orderContentAmount).divide(contentSum, 2, RoundingMode.DOWN);
                }
                //再计算分成额
                BigDecimal contentAmount = NumberUtil.mul(orderContentAmount, contentInfo
                        .getStablePercent()).divide(BigDecimal.valueOf(100d), 2, RoundingMode.DOWN);
                distributeContentAmount = distributeContentAmount.add(contentAmount);
                DistributeOrderTaskContent distributeOrderTaskContent = new DistributeOrderTaskContent();
                distributeOrderTaskContent.setDistributeTaskId(taskId);
                distributeOrderTaskContent.setDistributeUserId(contentInfo.getContentDistributeUserId());
                distributeOrderTaskContent.setOrderId(orderId);
                distributeOrderTaskContent.setContentSourceId(Long.valueOf(contentId));
                distributeOrderTaskContent.setOrderContentAmount(orderContentAmount);
                distributeOrderTaskContent.setDistributeRoleCode(distributeNodeInfo.getDistributeRoleCode());
                distributeOrderTaskContent.setDistributePercent(contentInfo.getStablePercent());
                distributeOrderTaskContent.setDistributeTime(new Date());
                distributeOrderTaskContent.setDistributeAmount(contentAmount);
                distributeOrderTaskContent.setSourceContentUserId(contentInfo.getAuthorUserId());
                distributeOrderTaskContent.setPayUserId(distributeOrderTask.getPayUserId());
                distributeOrderTaskContents.add(distributeOrderTaskContent);
            }
        } else {
            chainRecords = chainRecords + "全无";
        }
        //保存分成额度之和
        distributeOrderTask.setDistributeContentAmount(distributeContentAmount);
        return DistributeOrderContentCalResult.builder()
                .taskId(taskId)
                .orderId(orderId)
                .result(true)
                .message("内容处理成功：" + chainRecords)
                .distributeOrderTask(distributeOrderTask)
                .distributeOrderTaskContents(distributeOrderTaskContents)
                .build();
    }

    /**
     * method : calDistributeOrderTaskSale
     * description : 处理推广分销的计算
     *
     * @param taskId  \{@link Long \}
     * @param orderId \{@link Long \}
     * @author : Xiong weiqiang
     * @CreateDate : 2025-05-03 15:52:28
     * @Reviewed :
     * @UpdateLog : Name Date Reason/Contents
     * ---------------------------------------
     * **** **** ****
     */
    private DistributeOrderSaleCalResult calDistributeOrderTaskSale(Long taskId, Long orderId) {
        DistributeOrderTask distributeOrderTask = distributeOrderTaskService.getById(taskId);
        BigDecimal distributeOrderAmount = distributeOrderTask.getDistributeOrderAmount();
        BigDecimal distributeSaleAmount = new BigDecimal(0);
        String chainRecords = "推广分成:";

        List<DistributeOrderTaskSale> distributeOrderTaskSales = new ArrayList<>();
        Long sourceSaleUserId = 0L;
        //销售佣金计算
        //首先，通过邀请和服务关系找到订单客户的分成人
        List<DistributeUserInvite> distributeUserInvites = distributeUserInviteService.list(Wrappers
                .lambdaQuery(DistributeUserInvite.class)
                .eq(DistributeUserInvite::getUserId, distributeOrderTask.getPayUserId())
                .eq(DistributeUserInvite::getDataStatus, DistributeDataValidEnum.STATUS_VALID.getStatus()));
        if (CollUtil.isEmpty(distributeUserInvites)) {
            distributeOrderTaskLogService.logError(taskId, orderId, "订单id:" + orderId + "没有找到订单客户的邀请人信息");
            return DistributeOrderSaleCalResult.builder()
                    .taskId(taskId)
                    .orderId(orderId)
                    .result(false)
                    .message("订单id:" + orderId + "没有找到订单客户的邀请人信息")
                    .build();
        } else if (distributeUserInvites.size() > 1) {
            distributeOrderTaskLogService.logError(taskId, orderId, "订单id:" + orderId + "邀请人信息多个" + JSONUtil
                    .toJsonStr(distributeUserInvites));
            return DistributeOrderSaleCalResult.builder()
                    .taskId(taskId)
                    .orderId(orderId)
                    .result(false)
                    .message("订单id:" + orderId + "邀请人信息多个" + JSONUtil
                            .toJsonStr(distributeUserInvites))
                    .build();
        } else {
            sourceSaleUserId = distributeUserInvites.getFirst().getInviteUserId();
            if (sourceSaleUserId == null || sourceSaleUserId == 0L) {
                chainRecords = chainRecords + "平台所属学员";
            } else {
                //修改为以直接邀请人inviteUserId作为分成人。
                // 修改20250503 订单的分成人，修改为直接邀请人inviteUserId作为分成人：saleUserId可以是员工，
                // 员工的distributeUserId上有不同，如果是员工，distributeUserId是加盟商，角色是分销商员工。其他是分给自己的。
                // distributeUserId如果跟分成人不一样，那么就是机构分成人（机构下的会员，员工）
                // distributeUserId如果跟分成人一样，那么就是机构自己发展的，或者是平台，平台会员发展的。
                // 市场经理是管理机构的，所以市场经理只能从机构分成。
                // 又产生了新的情况，如果分销商员工禁用了，分销商还是得分成，还得记录。
                DistributeNodeInfo distributeNodeInfo = distributeNodeInfoService.getNodeInfoForUser(sourceSaleUserId, DistributeTypeEnum.TYPE_SALE);
                if (distributeNodeInfo == null) {
                    return DistributeOrderSaleCalResult.builder()
                            .taskId(taskId)
                            .orderId(orderId)
                            .result(false)
                            .message("订单id:" + orderId + "邀请人分销节点查询失败" + sourceSaleUserId)
                            .build();
                } else {
                    //找到分销链。
                    List<Long> userIdList = distributeNodeRoleChainService.selectSaleChainUserIds(sourceSaleUserId);
                    chainRecords = chainRecords + JSONUtil.toJsonStr(userIdList);
                    List<DistributeNodeRole> distributeNodeRoles = distributeNodeRoleService.list(Wrappers
                            .lambdaQuery(DistributeNodeRole.class)
                            .eq(DistributeNodeRole::getDataStatus, DistributeDataStatusEnum.STATUS_CURT.getStatus())
                            .in(DistributeNodeRole::getUserId, userIdList)
                            .eq(DistributeNodeRole::getDistributeType, DistributeTypeEnum.TYPE_SALE
                                    .getType()));
                    List<DistributeNodeInfo> distributeNodeInfos = distributeNodeInfoService.list(Wrappers
                            .lambdaQuery(DistributeNodeInfo.class)
                            .eq(DistributeNodeInfo::getDataStatus, DistributeDataStatusEnum.STATUS_CURT.getStatus())
                            .in(DistributeNodeInfo::getUserId, userIdList)
                            .eq(DistributeNodeInfo::getDistributeType, DistributeTypeEnum.TYPE_SALE
                                    .getType()));
                    //分销商员工的处理
                    if (DistributeSaleRoleEnum.ROLE_DSPD_EMP.getCode().equals(distributeNodeInfo.getDistributeRoleCode())) {
                        //先删除员工这个分销角色，后面再改回来
                        distributeNodeRoles.removeIf(a -> a.getUserId().equals(distributeNodeInfo.getUserId()));
                        distributeNodeInfos.removeIf(a -> a.getUserId().equals(distributeNodeInfo.getUserId()));
                    }
                    //找出了分成的人，那么还要管分销商，下面是不是有会员，有会员从分销商里分成
                    if (CollUtil.isEmpty(distributeNodeRoles)) {
                        distributeOrderTaskLogService.logError(taskId, orderId, "订单id:" + orderId + "邀请人无分销角色" + JSONUtil
                                .toJsonStr(userIdList));
                        //平台已经排除了，如果还没有就不对了。
                        return DistributeOrderSaleCalResult.builder()
                                .taskId(taskId)
                                .orderId(orderId)
                                .result(false)
                                .message("订单id:" + orderId + "邀请人无分销角色" + JSONUtil
                                        .toJsonStr(userIdList))
                                .build();
                    } else {

                        BigDecimal vipAmount = BigDecimal.ZERO;
                        BigDecimal vipPercent = BigDecimal.ZERO;
                        for (DistributeNodeRole role : distributeNodeRoles) {

                            BigDecimal saleAmount = NumberUtil.mul(distributeOrderAmount, role.getPercentStable()).divide(BigDecimal.valueOf(100d), 2, RoundingMode.DOWN);
                            //会员有登记，那么记录一下数据
                            if (role.getRoleCode().equals(DistributeSaleRoleEnum.ROLE_SLMB.getCode())) {
                                vipAmount = vipAmount.add(saleAmount);
                                vipPercent = vipPercent.add(role.getPercentStable());
                            }
                            distributeSaleAmount = distributeSaleAmount.add(saleAmount);
                            DistributeOrderTaskSale distributeOrderTaskSale = new DistributeOrderTaskSale();
                            distributeOrderTaskSale.setDistributeTaskId(taskId);
                            distributeOrderTaskSale.setOrderId(orderId);
                            distributeOrderTaskSale.setSaleUserId(sourceSaleUserId);
                            distributeOrderTaskSale.setDeductFlag(DistributeOrderDeductFlagEnum.STATUS_NO.getFlag());
                            distributeOrderTaskSale.setDistributeUserId(role.getUserId());
                            distributeOrderTaskSale.setDistributeRoleCode(role.getRoleCode());
                            distributeOrderTaskSale.setDistributePercent(role.getPercentStable());
                            distributeOrderTaskSale.setDistributeAmount(saleAmount);
                            distributeOrderTaskSale.setSourceUserId(distributeUserInvites.getFirst().getInviteUserId());
                            distributeOrderTaskSale.setDistributeTime(new Date());
                            distributeOrderTaskSales.add(distributeOrderTaskSale);
                        }
                        //找出加盟商的分成记录
                        List<DistributeOrderTaskSale> dpspDistributeOrderTaskSales = distributeOrderTaskSales.stream()
                                .filter(item -> item.getDistributeRoleCode()
                                        .equals(DistributeSaleRoleEnum.ROLE_DSPD.getCode()))
                                .collect(Collectors.toList());
                        //有加盟商，加盟商内部还要处理一阵。
                        if (CollUtil.isNotEmpty(dpspDistributeOrderTaskSales)) {
                            if (dpspDistributeOrderTaskSales.size() == 1) {
                                Map<Long, DistributeNodeInfo> orderSaleNodeMap = distributeNodeInfos.stream()
                                        .collect(Collectors.toMap(DistributeNodeInfo::getUserId, item -> item));
                                //回过头来处理分成
                                if (DistributeSaleRoleEnum.ROLE_DSPD_EMP.getCode().equals(distributeNodeInfo.getDistributeRoleCode())) {
                                    if (!orderSaleNodeMap.containsKey(distributeNodeInfo.getAdminUserId())) {
                                        return DistributeOrderSaleCalResult.builder()
                                                .taskId(taskId)
                                                .orderId(orderId)
                                                .result(false)
                                                .message("订单id:" + orderId + "员工供应商对不上：" + JSONUtil
                                                        .toJsonStr(distributeNodeInfo) + ",分销商：" + dpspDistributeOrderTaskSales.getFirst().getDistributeUserId())
                                                .build();
                                    }
                                    DistributeNodeInfo adminNodeInfo = orderSaleNodeMap.get(distributeNodeInfo.getAdminUserId());
                                    //禁用了不结算
                                    if (!adminNodeInfo.getEnableStatus().equals(DisEnableStatusEnum.ENABLE.getValue())) {
                                        chainRecords = chainRecords + ",员工记录：加盟商禁用，员工也没有分成，" + JSONUtil.toJsonStr(adminNodeInfo);
                                    } else {
                                        if (!distributeNodeInfo.getEnableStatus().equals(DisEnableStatusEnum.ENABLE.getValue())) {
                                            chainRecords = chainRecords + ",员工记录：禁用，记录在加盟商那，" + distributeNodeInfo.getUserId();
                                        } else {
                                            distributeOrderTaskSales.stream().forEach(item -> {
                                                if (item.getDistributeRoleCode()
                                                        .equals(DistributeSaleRoleEnum.ROLE_DSPD.getCode())) {
                                                    item.setDistributeRoleCode(DistributeSaleRoleEnum.ROLE_DSPD_EMP.getCode());
                                                }
                                            });
                                        }
                                    }
                                } else if (DistributeSaleRoleEnum.ROLE_SLMB.getCode().equals(distributeNodeInfo.getDistributeRoleCode())) {
                                    //会员本身是起始节点
                                    //如果加盟商体系里有会员，那么会员的分成要扣到加盟商上
                                    final BigDecimal VIP = BigDecimal.ZERO.add(vipAmount);
                                    final BigDecimal VIP_PERCENT = BigDecimal.ZERO.add(vipPercent);
                                    if (vipPercent.compareTo(dpspDistributeOrderTaskSales.getFirst()
                                            .getDistributePercent()) >= 0) {
                                        return DistributeOrderSaleCalResult.builder()
                                                .taskId(taskId)
                                                .orderId(orderId)
                                                .result(false)
                                                .message("订单id:" + orderId + "订单id:" + orderId + "会员分成大于供应商。会员分成：" + vipPercent + ",供应商分成：" + dpspDistributeOrderTaskSales
                                                        .getFirst()
                                                        .getDistributePercent())
                                                .build();
                                    }
                                    //有会员，有加盟商，扣下会员的钱
                                    distributeOrderTaskSales.forEach(item -> {
                                        if (item.getDistributeRoleCode().equals(DistributeSaleRoleEnum.ROLE_DSPD.getCode())) {
                                            item.setDistributeAmount(item.getDistributeAmount().subtract(VIP));
                                            item.setDistributePercent(item.getDistributePercent().subtract(VIP_PERCENT));
                                            item.setDeductFlag(DistributeOrderDeductFlagEnum.STATUS_YES.getFlag());
                                        }
                                    });
                                }
                            } else {
                                return DistributeOrderSaleCalResult.builder()
                                        .taskId(taskId)
                                        .orderId(orderId)
                                        .result(false)
                                        .message("订单id:" + orderId + "订单id:" + orderId + "供应商超过1个：" + JSONUtil
                                                .toJsonStr(dpspDistributeOrderTaskSales))
                                        .build();
                            }
                        }
                    }
                }
            }
            //支付人的邀请人，不一定是第一收益人
            distributeOrderTask.setSourceSaleUserId(sourceSaleUserId);
            distributeOrderTask.setDistributeContentAmount(BigDecimal.ZERO);
            distributeOrderTask.setDistributeSaleAmount(distributeSaleAmount);
            distributeOrderTask.setDataStatus(STATUS_ASGNED.getStatus());
            distributeOrderTask.setBalanceTime(ObjUtil.defaultIfNull(distributeOrderTask.getDistributeTime(), new Date()));
            return DistributeOrderSaleCalResult.builder()
                    .taskId(taskId)
                    .orderId(orderId)
                    .result(true)
                    .message("处理成功" + chainRecords)
                    .distributeOrderTask(distributeOrderTask)
                    .distributeOrderTaskSales(distributeOrderTaskSales)
                    .build();

        }
    }

    @Transactional
    @Override
    public void processMemberDistributeOrderTask(Long taskId, Long orderId) {
        ZLock zLock = null;
        try {
            zLock = distributedLock.tryLock(DistributeBusinessLockKeyCs.DISTRIBUTE_ORDER_TASK_CAL_LOCK_KEY + taskId, 3, TimeUnit.SECONDS);
            if (zLock == null) {
                throw new LockException("订单任务分销计算失败：获取锁失败");
            }
            DistributeOrderTask distributeOrderTask = distributeOrderTaskService.getById(taskId);

            if (distributeOrderTask == null) {
                distributeOrderTaskLogService.logError(taskId, orderId, "订单id:" + orderId + "没有找到订单任务信息");
                return;
            }
            if (!distributeOrderTask.getDataStatus().equals(STATUS_INASGN.getStatus())) {
                distributeOrderTaskLogService.logError(taskId, orderId, "订单id:" + orderId + "任务状态不匹配：" + distributeOrderTask
                        .getDataStatus());
                return;
            }

            DistributeOrderSaleCalResult distributeOrderSaleCalcResult = calDistributeOrderTaskSale(taskId, orderId);
            BigDecimal distributeOrderAmount = distributeOrderTask.getDistributeOrderAmount();
            BigDecimal distributeSaleAmount = distributeOrderSaleCalcResult.getDistributeOrderTask().getDistributeSaleAmount();

            if (!distributeOrderSaleCalcResult.getResult()) {
                distributeOrderTaskLogService.logError(taskId, orderId, distributeOrderSaleCalcResult.getMessage());
            } else {
                if (distributeOrderAmount.doubleValue() > ObjUtil.defaultIfNull(distributeSaleAmount, BigDecimal.ZERO).doubleValue()) {
                    DistributeOrderTask distributeOrderTaskFinal = distributeOrderSaleCalcResult.getDistributeOrderTask();
                    distributeOrderTaskFinal.setDistributeContentAmount(BigDecimal.ZERO);
                    String message = distributeOrderSaleCalcResult.getMessage();
                    distributeOrderTaskSaleService.saveBatch(distributeOrderSaleCalcResult.getDistributeOrderTaskSales());
                    distributeOrderTaskLogService.logSuccess(taskId, orderId, message);
                    distributeOrderTaskService.updateById(distributeOrderTaskFinal);
                } else {
                    distributeOrderTaskLogService.logError(taskId, orderId, "会员订单分成超过额度：销售分成总额：" + distributeSaleAmount);
                }
            }
        } catch (Exception e) {
            if (e instanceof LockException) {
                throw new BaseException("订单任务分销计算失败：任务忙");
            } else if (e instanceof BaseException) {
                throw (BaseException) e;
            } else {
                e.printStackTrace();
                throw new BaseException("订单任务分销计算失败：未知异常");
            }
        } finally {
            if (zLock != null) {
                try {
                    zLock.close();
                } catch (Exception e) {
                    throw new BaseException("订单任务分销计算失败：订单任务锁释放失败");
                }
            }
        }
    }

    @Transactional
    @Override
    public void processThirdProductDistributeOrderTask(Long taskId, Long orderId, String productId) {
        ZLock zLock = null;
        try {
            zLock = distributedLock.tryLock(DistributeBusinessLockKeyCs.DISTRIBUTE_ORDER_TASK_CAL_LOCK_KEY + taskId, 3, TimeUnit.SECONDS);
            if (zLock == null) {
                throw new LockException("第三方订单任务分销计算失败：获取锁失败");
            }
            DistributeOrderTask distributeOrderTask = distributeOrderTaskService.getById(taskId);
            if (distributeOrderTask == null) {
                distributeOrderTaskLogService.logError(taskId, orderId, "第三方订单id:" + orderId + "没有找到订单任务信息");
                return;
            }
            if (!distributeOrderTask.getDataStatus().equals(STATUS_INASGN.getStatus())) {
                distributeOrderTaskLogService.logError(taskId, orderId, "第三方订单id:" + orderId + "任务状态不匹配：" + distributeOrderTask
                        .getDataStatus());
                return;
            }
            if (StrUtil.isBlank(productId)) {
                distributeOrderTaskLogService.logError(taskId, orderId, "第三方订单id:" + orderId + "没有找到订单第三方产品信息");
                return;
            }
            //第三方内容分成
            DistributeOrderThirdProductCalResult distributeOrderThirdProductCalResult = calDistributeOrderTaskThirdProduct(taskId, orderId, Long.parseLong(productId));
            if (!distributeOrderThirdProductCalResult.getResult()) {
                distributeOrderTaskLogService.logError(taskId, orderId, distributeOrderThirdProductCalResult.getMessage());
            } else {
                DistributeOrderSaleCalResult distributeOrderSaleCalcResult = calDistributeOrderTaskSale(taskId, orderId);
                if (!distributeOrderSaleCalcResult.getResult()) {
                    distributeOrderTaskLogService.logError(taskId, orderId, distributeOrderSaleCalcResult.getMessage());
                } else {
                    BigDecimal distributeOrderAmount = distributeOrderTask.getDistributeOrderAmount();
                    BigDecimal distributeSaleAmount = distributeOrderSaleCalcResult.getDistributeOrderTask().getDistributeSaleAmount();
                    BigDecimal distributeContentAmount = distributeOrderThirdProductCalResult.getDistributeOrderTask().getDistributeContentAmount();
                    if (distributeOrderAmount.doubleValue() > (distributeSaleAmount.add(distributeContentAmount)).doubleValue()) {
                        DistributeOrderTask distributeOrderTaskFinal = distributeOrderSaleCalcResult.getDistributeOrderTask();
                        distributeOrderTaskFinal.setDistributeContentAmount(distributeContentAmount);
                        String message = distributeOrderThirdProductCalResult.getMessage().concat("|" + distributeOrderSaleCalcResult.getMessage());
                        distributeOrderTaskContentService.saveBatch(distributeOrderThirdProductCalResult.getDistributeOrderTaskContentList());
                        distributeOrderTaskSaleService.saveBatch(distributeOrderSaleCalcResult.getDistributeOrderTaskSales());
                        distributeOrderTaskLogService.logSuccess(taskId, orderId, message);
                        distributeOrderTaskService.updateById(distributeOrderTaskFinal);
                    } else {
                        distributeOrderTaskLogService.logError(taskId, orderId, "分成超过额度：销售分成总额：" + distributeSaleAmount + ",内容分成总额：" + distributeContentAmount);
                    }
                }

            }
        } catch (Exception e) {
            if (e instanceof LockException) {
                throw new BaseException("订单任务分销计算失败：任务忙");
            } else if (e instanceof BaseException) {
                throw (BaseException) e;
            } else {
                e.printStackTrace();
                throw new BaseException("订单任务分销计算失败：未知异常");
            }
        } finally {
            if (zLock != null) {
                try {
                    zLock.close();
                } catch (Exception e) {
                    throw new BaseException("订单任务分销计算失败：订单任务锁释放失败");
                }
            }
        }
    }

    private DistributeOrderThirdProductCalResult calDistributeOrderTaskThirdProduct(Long taskId, Long orderId,
                                                                                    Long productId) {
        DistributeOrderTask distributeOrderTask = distributeOrderTaskService.getById(taskId);
        StringBuilder chainRecords = new StringBuilder("第三方产品内容分成：");
        if (Arrays.asList(ProductType.PRODUCT_THIRD_CAP.name(), ProductType.PRODUCT_THIRD_YCBDC.name()).contains(distributeOrderTask.getProductType())) {
            List<DistributeContentProductThird> distributeContentProductThirds = distributeContentProductThirdService.list(Wrappers.lambdaQuery(DistributeContentProductThird.class)
                    .eq(DistributeContentProductThird::getProductId, productId)
                    .eq(DistributeContentProductThird::getDataStatus, 1)
            );
            //第三方产品也可能一对多，改造成多个内容配置分成
            if (CollUtil.isNotEmpty(distributeContentProductThirds)) {
                //循环内容配置情况
                //检查配置有效期和节点有效情况
                BigDecimal distributeContentOrderAmount = BigDecimal.ZERO;
                List<DistributeOrderTaskContent> distributeOrderTaskContentList = new ArrayList<>();
                for (DistributeContentProductThird distributeContentProductThird : distributeContentProductThirds) {
                    if (!DateUtil.isIn(new Date(), distributeContentProductThird.getValidStartTime(), distributeContentProductThird.getValidEndTime())) {
                        chainRecords.append("内容配置有效期不匹配：").append(distributeContentProductThird.getUserId()).append("|").append(distributeContentProductThird.getValidStartTime()).append("-").append(distributeContentProductThird.getValidEndTime()).append("|");
                        continue;
                    }
                    Long userId = distributeContentProductThird.getUserId();
                    if (userId != null) {
                        DistributeNodeInfo distributeNodeInfo = distributeNodeInfoService.getNodeInfoForUser(userId, DistributeTypeEnum.TYPE_CTPD);
                        if (distributeNodeInfo != null) {
                            if (distributeNodeInfo.getEnableStatus().equals(DisEnableStatusEnum.ENABLE.getValue())) {
                                BigDecimal stablePercent = ObjUtil.defaultIfNull(distributeContentProductThird.getStablePercent(), BigDecimal.ZERO);
                                BigDecimal contentAmount = NumberUtil.mul(distributeOrderTask.getDistributeOrderAmount(), stablePercent).divide(BigDecimal.valueOf(100d), 2, RoundingMode.DOWN);
                                DistributeOrderTaskContent distributeOrderTaskContent = new DistributeOrderTaskContent();
                                distributeOrderTaskContent.setDistributeTaskId(taskId);
                                distributeOrderTaskContent.setOrderId(orderId);
                                distributeOrderTaskContent.setContentSourceId(productId);
                                distributeOrderTaskContent.setOrderContentAmount(distributeOrderTask.getDistributeOrderAmount());
                                distributeOrderTaskContent.setDistributeRoleCode(distributeNodeInfo.getDistributeRoleCode());
                                distributeOrderTaskContent.setDistributePercent(stablePercent);
                                distributeOrderTaskContent.setDistributeTime(new Date());
                                distributeOrderTaskContent.setDistributeAmount(contentAmount);
                                distributeOrderTaskContent.setSourceContentUserId(distributeNodeInfo.getUserId());
                                distributeOrderTaskContent.setDistributeUserId(distributeContentProductThird.getContentDistributeUserId());
                                distributeOrderTaskContent.setPayUserId(distributeOrderTask.getPayUserId());
                                distributeOrderTask.setDistributeContentAmount(contentAmount);
                                chainRecords.append("用户id:").append(userId).append("，比例:").append(stablePercent).append("%");
                                distributeContentOrderAmount = distributeContentOrderAmount.add(contentAmount);
                                distributeOrderTaskContentList.add(distributeOrderTaskContent);
                            } else {
                                chainRecords.append("用户id:").append(userId).append("，禁用");
                            }
                        } else {
                            return DistributeOrderThirdProductCalResult.builder()
                                    .taskId(taskId)
                                    .orderId(orderId)
                                    .result(false)
                                    .message("任务id:" + taskId + "订单id:" + orderId + "第三方产品绑定内容节点为空：产品id" + productId)
                                    .build();
                        }
                    } else {
                        return DistributeOrderThirdProductCalResult.builder()
                                .taskId(taskId)
                                .orderId(orderId)
                                .result(false)
                                .message("任务id:" + taskId + "订单id:" + orderId + "第三方产品绑定用户出错：产品id" + productId)
                                .build();
                    }
                }
                distributeOrderTask.setDistributeContentAmount(distributeContentOrderAmount);
                return DistributeOrderThirdProductCalResult.builder()
                        .taskId(taskId)
                        .orderId(orderId)
                        .result(true)
                        .distributeOrderTask(distributeOrderTask)
                        .message(chainRecords.toString())
                        .distributeOrderTaskContentList(distributeOrderTaskContentList)
                        .build();
            } else {
                return DistributeOrderThirdProductCalResult.builder()
                        .taskId(taskId)
                        .orderId(orderId)
                        .result(false)
                        .message("任务id:" + taskId + "订单id:" + orderId + "第三方产品绑定设置出错：产品id" + productId)
                        .build();
            }
        } else {
            return DistributeOrderThirdProductCalResult.builder()
                    .taskId(taskId)
                    .orderId(orderId)
                    .result(false)
                    .message("任务id:" + taskId + "订单id:" + orderId + "第三方产品类型超出范围" + productId)
                    .build();
        }
    }

}